/* global window */
import modelExtend from 'dva-model-extend'
import pathToRegexp from 'path-to-regexp'
import * as basicData from 'services/basicData.js'
import { query, update } from 'services/reportBase.js'
import { message } from 'antd'
import { detailModel } from './common'

export default modelExtend(detailModel, {
  namespace: 'reportBase',

  state: {
    parentId: '',
    countryCodeData: [],
  },

  subscriptions: {
    setup ({ dispatch, history }) {
      history.listen((location) => {
        if (location.pathname === '/reportbase') {
          dispatch({ type: 'query' })
          dispatch({ type: 'iniBasicData' })
        }
      })
    },
  },

  effects: {
    * query ({ payload = {} }, { call, put }) {
      const data = yield call(query, payload)
      let resData = {}
      if (data.success) {
        if (!data.data) {
          resData = {
            editType: 'create',
            data: {},
          }
        } else {
          resData = {
            editType: 'update',
            data: data.data,
          }
        }
        yield put({
          type: 'updateState',
          payload: { ...resData },
        })
      }
    },

    * update ({ payload }, { select, call, put }) {
      const { parentId } = yield select(_ => _.reportBase)
      payload.entityId = parentId
      const data = yield call(update, payload)
      if (data.success) {
        message.success('update success')
        yield put({ type: 'query', payload: { id: parentId } })
      } else {
        message.error('update falied')
        throw data
      }
    },


    * iniBasicData ({ payload = {} }, { call, put }) {
      const countryCode = yield call(basicData.listall, { type: 'CountryCodes' })
      if (countryCode.success) {
        yield put({
          type: 'updateState',
          payload: {
            countryCodeData: countryCode.data,
          },
        })
      }
    },
  },

  reducers: {
  },
})
